const koa = require('koa')
const koaBody = require('koa-body')
const error = require('koa-json-error')
const parameter = require('koa-parameter')
const koaStatic = require('koa-static')
const path = require('path')
const routing = require('./routes')
const { connectionStr } = require('./config')
const mongoose = require('mongoose')
const logger = require('./logger')

const app = new koa()
app.use(logger())

mongoose.connect(connectionStr, () => {
  console.log('MongoDB connect success')
})
mongoose.connection.on('err', console.error)

app.use(koaStatic(path.join(__dirname, 'public')))

app.use(error({
  postFormat: (e, { stack, ...rest }) =>
    process.env.NODE_ENV === 'production' ?
      rest : { stack, ...rest }
}))

app.use(koaBody({
  multipart: true,
  formidable: {
    uploadDir: path.join(__dirname, '/public/uploads'),
    keepExtensions: true
  }
}))

app.use(parameter(app))

routing(app)

app.listen(3000, () => console.log('listen 3000 port'))
